import _ from 'lodash';
import { useReducer } from 'react';

/**
 * 定义初始状态信息
 */
export interface IstateType {
  assetForm: any; // 当前表单数据
  assetList: any; // 选择的资产数据列表
  materialList: any; // 选择的材料数据列表
  isEdit: boolean; // 是否可以编辑
  selectUserInfo: Record<string, any>; // 选中的使用人对象
}

/**
 * 新增和编辑页面操作枚举
 * @CLEAR_RECEIVE  清空存入 数据
 * @SELECT_MATERIEL 选中的材料数据列表
 *
 */
export enum IUseOAActionEnum {
  SELECT_ASSET = 'selectAsset',
  SELECT_MATERIAL = 'selectMaterial',
  CLEAR_RECEIVE = 'clearReceive',
  ASSET_FORM = 'assetForm',
  EDIT_STATUS = 'editStatus',
  SELECT_USER_INFO = 'selectUserInfo',
}

/**
 * 定义新增和编辑页面操作匹配
 * @type 操作类型
 * @payload 传递数据
 */
export interface IActionType {
  type: IUseOAActionEnum;
  payload?: any;
}

export const useOAReducer = () => {
  /** 初始化状态 */
  const initState: IstateType = {
    assetForm: {},
    assetList: [],
    materialList: [],
    isEdit: false,
    selectUserInfo: {},
  };

  const useOAManageReducer = (state: IstateType, action: IActionType) => {
    switch (action?.type) {
      /** 选中的资产 */
      case IUseOAActionEnum.SELECT_ASSET:
        const temp = {
          ...state,
          assetList: action?.payload,
        };
        return temp;

      /** 选中的材料 */
      case IUseOAActionEnum.SELECT_MATERIAL:
        return {
          ...state,
          materialList: action?.payload,
        };

      /** 选中的资产信息 */
      case IUseOAActionEnum.ASSET_FORM:
        return {
          ...state,
          assetForm: action?.payload,
        };

      /** 更新编辑状态 */
      case IUseOAActionEnum.EDIT_STATUS:
        return {
          ...state,
          isEdit: action?.payload,
        };

      /** 更新编辑状态 */
      case IUseOAActionEnum.SELECT_USER_INFO:
        return {
          ...state,
          selectUserInfo: action?.payload,
        };

      /**
       *  清空已选数据
       */
      case IUseOAActionEnum.CLEAR_RECEIVE:
        return {
          ...state,
          assetForm: {},
          assetList: [],
          materialList: [],
          isEdit: false,
        };

      default:
        return {
          ...state,
          ...initState,
        };
    }
  };

  const [state, useOADispatch] = useReducer(useOAManageReducer, initState);

  return {
    ...state,
    useOADispatch,
  };
};
